package com.ccp.dev.system.configuration;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.unit.DataSize;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Enumeration;

/**
 * ClassDescribe:拦截器
 * @author :jiayueqiao
 * Date: 2019-12-02
 * Since:1
 */
@Component
public class CommonInterceptor implements HandlerInterceptor {

    @Value("${spring.servlet.multipart.max-file-size}")
    private DataSize multipartMaxSize;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String ctx = httpServletRequest.getContextPath();
        httpServletRequest.setAttribute("ctx", ctx);
        //上传文件的最大限制
        httpServletRequest.setAttribute("multipartMaxSize", String.valueOf(multipartMaxSize.toKilobytes()));

        // 前端重定向配置
        // 允许跨域请求
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        HttpSession session = httpServletRequest.getSession();
        Enumeration<String> attributeNames = session.getAttributeNames();
        if (!attributeNames.hasMoreElements()) {
            requestDirect(httpServletRequest, httpServletResponse);
        }
        return true;
    }

    /**
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void requestDirect(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取当前请求路径
        String basePath = request.getScheme() + "://" + request.getServerName() + ":"  + request.getServerPort()+request.getContextPath();
        // 如果request.getHeader("X-Requested-With") 返回的是"XMLHttpRequest"说明就是ajax请求
        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
            // 前端需要判断是否是重定向
            response.setHeader("REDIRECT","REDIRECT");
            // 需要重定向的路径
            response.setHeader("CONTENTPATH", basePath);
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
